'use strict';

function exploreCtrl($scope, $http) {

  var filter = $scope.filter = {
    category: [],
    rating: null
  };

  var allUsers;
  
 $http.get('search').success(function(data) {
		allUsers = data;
		$scope.users = allUsers;
 });
  
  
  $scope.$watch('filter', filterAndSortUsers, true);

  function filterAndSortUsers() {
    $scope.users = [];

    // filter
    angular.forEach(allUsers, function(item) {


      if (filter.rating && filter.rating !== item.rating) {
        return;
      }

      if (filter.category.length && filter.category.indexOf(item.category) === -1) {
        return;
      }

      $scope.users.push(item);
    });


    // sort
    $scope.users.sort(function(a, b) {
      if (a[filter.sortBy] > b[filter.sortBy]) {
        return filter.sortAsc ? 1 : -1;
      }

      if (a[filter.sortBy] < b[filter.sortBy]) {
        return filter.sortAsc ? -1 : 1;
      }

      return 0;
    });
  };


  $scope.sortBy = function(key) {
    if (filter.sortBy === key) {
      filter.sortAsc = !filter.sortAsc;
    } else {
      filter.sortBy = key;
      filter.sortAsc = true;
    }
  };


  $scope.sortIconFor = function(key) {
    if (filter.sortBy !== key) {
      return '';
    }

    return filter.sortAsc ? '\u25B2' : '\u25BC';
  };

  $http.get('category').success(function(data) {
    $scope.CATEGORIES = data;

  });

}

exploreCtrl.$inject = ['$scope','$http'];
